//
//  HMRefreshControl.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/5.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum HMRefreshType : String {
    case normal = "normal"
    case pulling = "pulling"
    case refreshing = "refreshing"
}

private let HMRefreshControlH: CGFloat = 50

class HMRefreshControl: UIControl {
    
    // 记录刷新控件状态的属性，默认为默认状态
    var refreshState : HMRefreshType = .normal{
        didSet{
            switch refreshState {
            case .pulling:
                // 调转箭头
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                // 更改文字 --> 松开起
                self.messageLabel.text = "松开起飞"
            case .normal:
                // 进入到默认状态应该将菊花转停止掉
                indicatorView.stopAnimating()
                // 简单显示出来
                arrowIcon.isHidden = false
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.arrowIcon.transform = CGAffineTransform.identity
                    })
                }
                self.messageLabel.text = "等待起飞"
            case .refreshing:
                // 把箭头隐藏，显示菊花转
                arrowIcon.isHidden = true
                indicatorView.startAnimating()
                self.messageLabel.text = "正在起飞"
                UIView.animate(withDuration: 0.25, animations: { 
                    var inset = self.scrollView!.contentInset
                    inset.top += HMRefreshControlH
                    self.scrollView!.contentInset = inset
                })
                
                sendActions(for: UIControlEvents.valueChanged)
            
            }
        }
    }
    
    // 记录其父控件
    weak var scrollView: UIScrollView?
    
    func endRefreshing() {
        // ?? 要将状态改成normal
        refreshState = .normal
    }

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.purple
        
        // 大小？ --> width / height
        frame.size = CGSize(width: HMScreenW, height: HMRefreshControlH)
        frame.origin.y = -HMRefreshControlH
        
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)

        arrowIcon.snp_makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowIcon.snp_trailing)
            make.centerY.equalTo(arrowIcon)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }


    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if newSuperview is UIScrollView{
            // 1. 记录
            self.scrollView = newSuperview as? UIScrollView
            // 2. 为这个scrollView添加观察者
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
            
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentInsetTop = self.scrollView!.contentInset.top
        // 如果小于这个值，就代表当前控件已经完全显示出来了
        let conditionValue: CGFloat = -contentInsetTop - HMRefreshControlH
        // idDragging 代表用户是否在拖动
        if scrollView!.isDragging {
            if refreshState == .normal && self.scrollView!.contentOffset.y <= conditionValue {
                print("进入到松手就刷新的状态")
                self.refreshState = .pulling
            }else if refreshState == .pulling && self.scrollView!.contentOffset.y > conditionValue{
                print("进入到默认状态")
                self.refreshState = .normal

        }else{
            if refreshState == .pulling {
                refreshState = .refreshing
            }
        }
    }
    }
    
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // MARK: - 懒加载控件
    private lazy var indicatorView: UIActivityIndicatorView = {
        let v = UIActivityIndicatorView()
        // 默认隐藏
        v.color = UIColor.black
        return v
    }()

   private var arrowIcon:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
   lazy var messageLabel:UILabel = {
        let label = UILabel(textColor: UIColor.black, fontSize: 12)
        label.text = "等待起飞"
        return label
    }()

    
}
